<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>工具AI</title>
    <!--<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>-->
    <style>
        #chat-container {
            /*max-width: 100%;*/
            width: 100%;
            margin: 0 auto;
            padding: 20px;
        }

        #messages {
            width: 90%;
            height: 600px;
            border: 1px solid #ddd;
            overflow-y: auto;
            padding: 10px;
            margin-bottom: 10px;
        }

        #message-input {
            width: 70%;
            padding: 8px;
        }

        #send-button {
            padding: 8px 15px;
        }

        #edit-button {
            padding: 8px 15px;
        }

        .markdown-body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        /* 关键样式：处理换行和空白 */
        .markdown-body p {
            white-space: pre-wrap; /* 保留换行和空格 */
            margin: 1em 0; /* 段落间距 */
        }

        .markdown-body br {
            content: ""; /* 确保br换行生效 */
            display: block;
            margin-bottom: 0.5em; /* 换行间距 */
        }

        /* 使下拉框单独占据一行 */
        .select-container {
            display: block;
            margin: 20px 0;
            width: 100%;
        }

        /* 基础美化 */
        .styled-select {
            display: block;
            width: 100%;
            max-width: 400px;
            padding: 12px 15px;
            font-size: 16px;
            line-height: 1.5;
            color: #495057;
            background-color: #fff;
            background-image: none;
            border: 1px solid #ced4da;
            border-radius: 6px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
            appearance: none; /* 移除默认箭头 */
            -webkit-appearance: none;
            -moz-appearance: none;
        }

    </style>
</head>
<body>
<div id="chat-container">
    <div id="messages" style="width: 95%"></div>
    <div id="jsonMessages" style="width: 40%"></div>
    <select id="toolId" class="select-container styled-select">
        <option value="">请选择工具</option>
        <option value="1">数据库查询</option>
        <option value="2">天气查询</option>
    </select>
    <label for="message-input"></label><input type="text" id="message-input" placeholder="输入消息...">
    <button id="send-button">发送</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/markdown-it/dist/markdown-it.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
    // 创建markdown-it实例
    const md = window.markdownit({
        html: true,        // 允许HTML标签
        breaks: true,      // 转换换行符为<br>
        linkify: true     // 自动转换URL为链接
    });

    const messagesContainer = document.getElementById('messages');
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');
    // 添加消息到聊天界面
    function addMessage(content, isUser) {
        const messageDiv = document.createElement('div');
        messageDiv.className = isUser ? 'user-message' : 'ai-message';
        messageDiv.style.margin = '5px 0';
        messageDiv.style.padding = '8px 12px';
        messageDiv.style.borderRadius = '10px';
        messageDiv.style.backgroundColor = isUser ? '#e3f2fd' : '#f5f5f5';
        messageDiv.style.alignSelf = isUser ? 'flex-end' : 'flex-start';
        messageDiv.style.width = '80%';
        messageDiv.textContent = content;
        messagesContainer.appendChild(messageDiv);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }


    // 处理流式响应
    async function streamChat(message) {
        addMessage(message, true);
        messageInput.value = '';

        const responseDiv = document.createElement('div');
        responseDiv.style.display = 'display: inline-block'
        responseDiv.className = 'ai-message';
        responseDiv.style.width = '90%';
        responseDiv.style.maxWidth = '90%';
        responseDiv.style.margin = '5px 0';
        responseDiv.style.padding = '8px 12px';
        responseDiv.style.borderRadius = '10px';
        responseDiv.style.backgroundColor = '#f5f5f5';
        responseDiv.className = 'markdown-body'; // 添加单个类


        /*const jsonResponseDiv = document.createElement('jsonDiv');
        jsonResponseDiv.style.display = 'display: inline-block'
        jsonResponseDiv.className = 'ai-message';
        jsonResponseDiv.style.width = '50%';
        jsonResponseDiv.style.maxWidth = '50%';
        jsonResponseDiv.style.margin = '5px 0';
        jsonResponseDiv.style.padding = '8px 12px';
        jsonResponseDiv.style.borderRadius = '10px';
        jsonResponseDiv.style.backgroundColor = '#f5f5f5';
        jsonResponseDiv.className = 'markdown-body'; // 添加单个类*/

        messagesContainer.appendChild(responseDiv);
        //messagesContainer.appendChild(jsonResponseDiv);

        let url = '/tool/streamChat?chatId=67&message=' + encodeURIComponent(message);
        let toolId = document.getElementById('toolId').value;
        if (toolId != null && toolId !== 'undefined') {
            /*let syncUrl = '/ai/chat?chatId=67&message=' + encodeURIComponent(message);
            syncUrl = syncUrl + "&businessId=" + businessId;

            axios.get(syncUrl)
                .then(response => {
                    console.log('Success:', response.data.data);
                    responseDiv.innerHTML = md.render(response.data.data);
                    messagesContainer.scrollTop = messagesContainer.scrollHeight;
                })
                .catch(error => {
                    console.error('Error:', error);
                });*/

            url = url + "&toolId=" + toolId;
            try {
                const response = await fetch(url, {
                    headers: {
                        'Accept': 'text/event-stream'
                    }
                });

                if (!response.ok) {
                    throw new Error('请求失败');
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                let accumulatedText = '';
                let jsonAccumulatedText = '';
                const topics = [];
                while (true) {
                    const {done, value} = await reader.read();
                    if (done) break;

                    buffer += decoder.decode(value, {stream: true});
                    // 使用正则表达式移除 "data:" 及可能的空白字符
                    //accumulatedText = accumulatedText.replace(/^data:\s*!/g, '');

                    // 按行分割处理
                    const lines = buffer.split(/\r\n|\n|\r/);
                    buffer = lines.pop(); // 保留未完成的行
                    for (const line of lines) {
                        if (line.startsWith('data:')) {
                            const data = line.substring(5).trim();
                            if (data) { // 忽略空数据
                                let res = JSON.parse(data);
                                //console.log('Parsed data:', res);
                                if ("message" === res.event) {
                                    accumulatedText = accumulatedText + res.data;
                                } else if ("jsonMessage" === res.event) {
                                    jsonAccumulatedText = jsonAccumulatedText + JSON.stringify(res.data) + "\n";
                                    topics.push(res.data);
                                } else if ("end" === res.event) {
                                    //console.log(JSON.stringify(toipcs));
                                    localStorage.setItem("singleChoiceQuestionContent", JSON.stringify(topics))
                                }
                            }
                        }
                    }
                    // 处理最后剩余的数据
                    /*if (buffer.startsWith('data:')) {
                        const data = buffer.substring(5).trim();
                        if (data) {
                            console.log('Final data:', data);
                        }
                    }*/

                    responseDiv.innerHTML = md.render(accumulatedText);
                    //jsonResponseDiv.innerHTML = md.render(jsonAccumulatedText);
                    messagesContainer.scrollTop = messagesContainer.scrollHeight;
                }
            } catch (error) {
                console.error('Error:', error);
                responseDiv.textContent = '发生错误: ' + error.message;
            }
        } else {
            try {
                const response = await fetch(url, {
                    headers: {
                        'Accept': 'text/event-stream'
                    }
                });

                if (!response.ok) {
                    throw new Error('请求失败');
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                let accumulatedText = '';
                while (true) {
                    const {done, value} = await reader.read();
                    if (done) break;

                    buffer += decoder.decode(value, {stream: true});
                    // 使用正则表达式移除 "data:" 及可能的空白字符
                    //accumulatedText = accumulatedText.replace(/^data:\s*!/g, '');

                    // 按行分割处理
                    const lines = buffer.split(/\r\n|\n|\r/);
                    buffer = lines.pop(); // 保留未完成的行
                    for (const line of lines) {
                        if (line.startsWith('data:')) {
                            const data = line.substring(5).trim();
                            if (data) { // 忽略空数据
                                let res = JSON.parse(data);
                                //console.log('Parsed data:', res);
                                if ("message" === res.event) {
                                    accumulatedText = accumulatedText + res.data;
                                }
                            }
                        }
                    }
                    // 处理最后剩余的数据
                    /*if (buffer.startsWith('data:')) {
                        const data = buffer.substring(5).trim();
                        if (data) {
                            console.log('Final data:', data);
                        }
                    }*/

                    responseDiv.innerHTML = md.render(accumulatedText);
                    messagesContainer.scrollTop = messagesContainer.scrollHeight;
                }
            } catch (error) {
                console.error('Error:', error);
                responseDiv.textContent = '发生错误: ' + error.message;
            }
        }

    }
    // 发送消息
    sendButton.addEventListener('click', () => {
        const message = messageInput.value.trim();
        if (message) {
            streamChat(message);
        }
    });

    // 按Enter键发送
    messageInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            const message = messageInput.value.trim();
            if (message) {
                streamChat(message);
            }
        }
    });
</script>
</body>
</html>